<template>
  <div class="app-container">
    <div class="layout-box">
      <div class="search-box">
        <!-- 搜索单据 -->
        <div class="search-input">
          <el-input
            class="input-data"
            placeholder="销售订单号"
            v-model="searchForm.ppNumber"
            style="width: 200px"
            v-if="detailStatus == true"
            clearable
          ></el-input>
          <el-input
            class="input-data"
            placeholder="单据编码"
            v-model="searchForm.mpCode"
            style="width: 200px"
            clearable
          ></el-input>
          <el-input
            class="input-data"
            placeholder="物料编码"
            v-if="detailStatus == true"
            v-model="searchForm.invCode"
            clearable
          ></el-input>
          <el-input
            class="input-data"
            placeholder="物料名称"
            v-if="detailStatus == true"
            v-model="searchForm.invName"
            clearable
          ></el-input>
          <el-select
            class="picker-data"
            style="margin-right: 15px"
            placeholder="单据状态"
            v-if="detailStatus == false"
            clearable
            v-model="searchForm.invoiceStatus"
            @click.native="getInvoiceStatus()"
          >
            <el-option
              v-for="dict in optionsinvoiceStatus"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
          <el-select
            class="picker-data"
            placeholder="业务状态"
            style="margin-right: 15px"
            v-if="detailStatus == false"
            clearable
            v-model="searchForm.workStatus"
            @click.native="getWorkStatus()"
          >
            <el-option
              v-for="dict in optionsworkStatus"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
          <el-date-picker
            v-model="valueDate"
            type="daterange"
            align="right"
            unlink-panels
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            style="width: 250px"
          >
          </el-date-picker>
        </div>
        <div class="search-btn">
          <el-button
            v-if="detailStatus == false"
            type="primary"
            v-hasPermi="['mp:mbom:query']"
            icon="el-icon-search"
            @click="searchList('bill')"
            >搜索
          </el-button>
          <el-button
            v-if="detailStatus == true"
            type="primary"
            v-hasPermi="['mp:mbom:query']"
            icon="el-icon-search"
            @click="searchList('detail')"
            >搜索
          </el-button>
        </div>
      </div>
      <el-row :gutter="10" class="mb8" v-if="detailStatus == false">
        <div class="con-top">
          <div class="top-left">
            <el-col :span="1.5">
              <el-button
                type="primary"
                v-hasPermi="['mp:mbom:detail']"
                icon="el-icon-c-scale-to-original"
                size="mini"
                @click="detailView"
              >
                明细</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-menu"
                size="mini"
                @click="handleCheckleAll"
                >查询所有</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                v-hasPermi="['mp:mbom:entity:add']"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="jumpAdd"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                v-hasPermi="['mp:mbom:remove']"
                plain
                icon="el-icon-delete"
                size="mini"
                @click="batchDelete"
                :disabled="batchStatus"
              >
                删除</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                v-hasPermi="['mp:mbom:permit']"
                plain
                icon="el-icon-bell"
                size="mini"
                @click="batchExamine"
                :disabled="batchStatus"
                >审核
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                v-hasPermi="['mp:mbom:revoke']"
                plain
                icon="el-icon-close-notification"
                size="mini"
                @click="batchDeExamine"
                :disabled="batchStatus"
                >反审核</el-button
              >
            </el-col>
          </div>
        </div>
      </el-row>
      <el-row
        :gutter="10"
        class="mb8"
        v-if="detailStatus == true"
        style="display: flex; align-items: center; position: relative"
      >
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-document-remove"
            size="mini"
            @click="billView"
            >单据
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-menu"
            size="mini"
            @click="handleCheckleDetail"
            >查询所有</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            v-hasPermi="['mp:mbom:entity:add']"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="jumpAdd"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['mp:mbom:export']"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <!-- 单据列表 -->
      <el-table
        :data="tableData"
        ref="tableHeight"
        style="width: 100%"
        border
        v-loading="loading"
        :height="maxHeight"
        @selection-change="handleSelectionChange"
        v-if="detailStatus == false"
        :key="tableKey"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="selection" width="50" align="center">
        </el-table-column>
        <el-table-column prop="mpCode" label="单据编码" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.mpCode }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="invoiceDate"
          label="单据日期"
          align="center"
          sortable
        >
          <template v-slot="scope">
            <span>{{ scope.row.invoiceDate | inMaterTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="workStatus"
          label="单据状态"
          align="center"
          width="120"
        >
          <template v-slot="scope">
            <div class="order-status">
              <span
                v-if="scope.row.invoiceStatus == '0'"
                style="color: #e6a23c"
                >{{ scope.row.invoiceStatus | getInvoice }}</span
              >
              <span
                v-if="scope.row.invoiceStatus == '1'"
                style="color: #67c23a"
                >{{ scope.row.invoiceStatus | getInvoice }}</span
              >
              <span
                v-if="scope.row.invoiceStatus == '2'"
                style="color: #909399"
                >{{ scope.row.invoiceStatus | getInvoice }}</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="params.mp_mbom_type"
          label="业务类型"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="params.deptName"
          label="业务部门"
          align="center"
          width="150"
        >
        </el-table-column>
        <el-table-column
          prop="workStaff"
          label="业务人员"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="params.sys_work_status"
          label="业务状态"
          align="center"
          width="120"
        >
        </el-table-column>
        <el-table-column prop="checkDate" label="审核日期" align="center">
          <template v-slot="scope">
            <span v-if="scope.row.checkDate !== null">{{
              scope.row.checkDate | inMaterTime
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template v-slot="scope">
            <div class="public-btn">
              <el-link
                type="primary"
                v-hasPermi="['mp:mbom:entity:view']"
                @click="jumpDetail(scope.row.mpCode)"
                >查看
              </el-link>
              <el-link
                type="success"
                v-hasPermi="['mp:mbom:entity:edit']"
                @click="jumpUpdate(scope.row.mpCode)"
                :disabled="scope.row.invoiceStatus == '1'"
                >编辑</el-link
              >
              <el-link
                type="danger"
                v-hasPermi="['mp:mbom:remove']"
                :disabled="scope.row.invoiceStatus == '1'"
                @click="handleDelete(scope.row)"
              >
                删除</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 明细列表 -->
      <el-table
        v-if="detailStatus == true"
        ref="tableDetailHeight"
        :data="detailTableData"
        border
        style="width: 100%"
        v-loading="detailLoading"
        :row-class-name="tableRowClassName"
        :height="detailMaxHeight"
        :key="tableKey2"
      >
        <el-table-column type="index" width="50" align="center" label="序号">
        </el-table-column>
        <el-table-column
          prop="mpOrderCode"
          label="计划单号"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <div>
              <span
                v-if="
                  scope.row.mpOrderCode == '' || scope.row.mpOrderCode == null
                "
                class="el-icon-minus"
              ></span>
              <span v-else>{{ scope.row.mpOrderCode }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="ppNumber"
          label="销售订单号"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <div>
              <span
                v-if="scope.row.ppNumber == '' || scope.row.ppNumber == null"
                class="el-icon-minus"
              ></span>
              <span v-else>{{ scope.row.ppNumber }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="ppDate "
          label="订单交期"
          align="center"
          width="120"
        >
          <template v-slot="scope">
            <span
              v-if="scope.row.ppDate !== undefined && scope.row.ppDate !== null"
              >{{ scope.row.ppDate | inMaterTime }}</span
            >
          </template>
        </el-table-column>

        <el-table-column
          prop="mpCode"
          label="单据编码"
          align="center"
          width="130"
        >
          <template v-slot="scope">
            <div>
              <span
                style="color: #1890ff"
                @click="jumpDetail(scope.row.mpCode)"
                >{{ scope.row.mpCode }}</span
              >
            </div>
          </template>
        </el-table-column>
             <el-table-column
          prop="workStatus"
          label="单据状态"
          align="center"
          width="120"
        >
          <template v-slot="scope">
            <div class="order-status">
              <span
                v-if="scope.row.invoiceStatus == '0'"
                style="color: #e6a23c"
                >{{ scope.row.invoiceStatus | getInvoice }}</span
              >
              <span
                v-if="scope.row.invoiceStatus == '1'"
                style="color: #67c23a"
                >{{ scope.row.invoiceStatus | getInvoice }}</span
              >
              <span
                v-if="scope.row.invoiceStatus == '2'"
                style="color: #909399"
                >{{ scope.row.invoiceStatus | getInvoice }}</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="params.mp_mbom_type"
          label="业务类型"
          align="center"
          width="100"
        >
        </el-table-column>
        <el-table-column
          prop="invName"
          label="物料名称"
          align="center"
        >
          <template v-slot="scope">
            <div>
              <span
                v-if="scope.row.wiQuantity > 0"
                :style="
                  scope.row.invQuantity == scope.row.wiQuantity
                    ? 'color: #13ce66'
                    : 'color:#1890ff'
                "
                >{{ scope.row.invName }} {{ scope.row.invAttribute }}</span
              >
              <span v-else style="color: #606266"
                >{{ scope.row.invName }} {{ scope.row.invAttribute }}</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="invCode"
          label="物料编码"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="unitName"
          label="主计量"
          align="center"
          width="60"
        >
        </el-table-column>
        <el-table-column
          prop="invSupplyType"
          label="供应方式"
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <div class="piece-box">
              <el-select
                class="select-pack"
                v-model="scope.row.invSupplyType"
                placeholder=""
                disabled
              >
                <el-option
                  v-for="item in optionsSupplyType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="invQuantity"
          label="生产数量"
          align="center"
          width="120"
        >
          <template v-slot="scope">
            <div style="text-align: right">
              <span>{{ scope.row.invQuantity }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="date"
          label="单据日期"
          align="center"
          width="120"
        >
          <template v-slot="scope">
            <span
              v-if="
                scope.row.invoiceDate !== null &&
                scope.row.invoiceDate !== undefined
              "
              >{{ scope.row.invoiceDate | inMaterTime }}</span
            >
          </template>
        </el-table-column>
 
      </el-table>
      <!-- 详情抽屉 -->
      <el-drawer
        :title="drawerTitle"
        :visible.sync="drawer"
        :direction="direction"
        :before-close="handleClose"
        size="928px"
        class="po-drawer-detail"
      >
        <div class="drawer-list-box">
          <div class="drawer-table" v-if="materialStatus">
            <h2>订单信息</h2>
            <div class="table-border">
              <table
                class="table-left"
                cellspacing="0"
                style="background-color: #f7f7f8"
              >
                <tr>
                  <td>销售订单号</td>
                  <td>{{ drawerCustomer.omCode }}</td>
                </tr>
                <tr>
                  <td>销售员</td>
                  <td>{{ drawerCustomer.workStaff }}</td>
                </tr>
                <tr>
                  <td>订单交期</td>
                  <td>{{ drawerCustomer.deliverDate }}</td>
                </tr>
                <tr>
                  <td>交期状态</td>
                  <td>{{ drawerCustomer.deliverStatus | filterDeliver }}</td>
                </tr>
                <tr>
                  <td>业务类型</td>
                  <td>{{ drawerCustomer.workType }}</td>
                </tr>
              </table>
            </div>
          </div>
          <div class="drawer-table inv-table" v-if="drawerCustomer">
            <div class="drawer-next" v-if="materialStatus">
              <el-link
                type="primary"
                :disabled="drawerCustomer.omOrderSalveList.length == 1"
                @click="btnForward(drawerMaterial, 'last')"
                >上一条
              </el-link>
              <el-link
                type="primary"
                :disabled="drawerCustomer.omOrderSalveList.length == 1"
                @click="btnForward(drawerMaterial, 'next')"
                >下一条
              </el-link>
            </div>
            <el-tabs
              v-model="activeName"
              class="order-tab"
              v-if="materialStatus"
            >
              <el-tab-pane label="物料信息" name="first" class="table-right">
                <div class="drawer-content">
                  <div class="content-t">
                    <p>
                      <label>单据编码：</label>
                      <span>{{ drawerMaterial.omCode }}</span>
                    </p>
                  </div>
                  <div class="drawer-box">
                    <div class="awer-l">
                      <div class="content-t" style="height: 41px">
                        <p>
                          <label>物料编码：</label>
                          <span>{{ drawerMaterial.invCode }}</span>
                        </p>
                      </div>
                      <div class="content-t">
                        <p>
                          <label>包装规格：</label>
                          <span>{{ drawerMaterial.pkgType }}</span>
                        </p>
                      </div>
                      <div class="content-t">
                        <p>
                          <label>订单数量：</label>
                          <span
                            >{{ drawerMaterial.quantity }}
                            {{ drawerMaterial.unitName }}</span
                          >
                        </p>
                      </div>
                    </div>
                    <div class="awer-r">
                      <div class="content-t con-height">
                        <p>
                          <label>物料名称：</label>
                          <span
                            >{{ drawerMaterial.invName }}
                            {{ drawerMaterial.invAttribute }}
                            {{ drawerMaterial.densityCode }}
                          </span>
                        </p>
                      </div>
                      <div class="content-t">
                        <p>
                          <label>包装件数：</label>
                          <span>{{ drawerMaterial.piece }}</span>
                        </p>
                      </div>

                      <div class="content-t">
                        <p>
                          <label>发货数量：</label>
                          <span>{{ drawerMaterial.wiQuantity }}</span>
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="质量要求" name="second">
                <div class="tab-text">
                  <el-input
                    type="textarea"
                    :rows="2"
                    disabled
                    v-model="drawerMaterial.qualityRemarks"
                  >
                  </el-input>
                </div>
              </el-tab-pane>
              <el-tab-pane label="包装要求" name="third">
                <div class="tab-text">
                  <el-input
                    type="textarea"
                    :rows="2"
                    disabled
                    v-model="drawerMaterial.pkgRemarks"
                  >
                  </el-input>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <div class="drawer-detail-table">
          <el-table
            ref="tableDetailHeight"
            :data="drawerTableData"
            border
            style="width: 100%"
            v-loading="drawerTableLoading"
            :height="drawerTableMaxHeight"
            :row-class-name="tableRowClassName"
          >
            <el-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            >
            </el-table-column>
            <el-table-column
              prop="code"
              label="单据编码"
              align="center"
              width="110"
            >
              <template v-slot="scope">
                <div>
                  <span
                    style="color: #1890ff"
                    @click="handleViewBill(scope.row)"
                    >{{ scope.row.code }}</span
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="invoice_name"
              label="单据类型"
              align="center"
              width="95"
            >
            </el-table-column>
            <el-table-column
              prop="type_name"
              label="业务类型"
              align="center"
              width="80"
            >
            </el-table-column>
            <el-table-column
              prop="date"
              label="单据日期"
              align="center"
              width="100"
            >
            </el-table-column>
            <el-table-column
              prop="inv_code"
              label="物料编码"
              align="center"
              width="100"
            >
            </el-table-column>
            <el-table-column prop="inv_name" label="物料名称" align="center">
              <template v-slot="scope">
                <div>
                  <span
                    >{{ scope.row.inv_name }}
                    {{ scope.row.inv_attribute }}</span
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="unit_name"
              label="主计量"
              align="center"
              width="80"
            >
            </el-table-column>
            <el-table-column prop="quantity" label="数量" align="center">
              <template v-slot="scope">
                <div style="text-align: right">
                  <span>{{ scope.row.quantity }}</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-drawer>
    </div>

    <!-- 单据分页 -->
    <pagination
      v-if="total > 0 && detailStatus == false"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getBillList"
    />
    <!-- 明细分页 -->
    <pagination
      v-if="detailTotal > 0 && detailStatus == true"
      :total="detailTotal"
      :page.sync="queryDetail.pageNum"
      :limit.sync="queryDetail.pageSize"
      @pagination="getDetailList"
    />
  </div>
</template>

<script>
import {
  dictMatching, //字典
  listBill, //单据列表
  deleteBill, // 删除单条
  examineBill, //批量审核
  examineDeBill, //批量反审核
  billParameters,
  listDetail, //查询明细
  exportDetail, //明细导出
  listLink, //关联查询
  listCode, //订单号查询
} from "../../api/mbom";
import { Translate } from "../../utils/plan";
//并行请求
import axios from "axios";
export default {
  name: "Mbom",
  data() {
    return {
      // 单据遮罩层
      loading: true,
      // 单据查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        mpCode: "", //单据编码
        invoiceStatus: "",
        workStatus: "", //单据状态
        startDate: "",
        endDate: "",
        workType: this.$route.query.workType,
      },
      // 开始时间/结束时间配置
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      valueDate: "",
      //明细状态
      detailStatus: true,
      activeName: "first",
      //单据表格key
      tableKey: "",
      // 搜索单据
      searchForm: {
        mpCode: "", //订单号
        ppNumber: "", //销售单号
        startDate: "",
        endDate: "",
        workStatus: "",
        invoiceStatus: "",
        invName: "", //物料名称
        invCode: "", //物料编码
      },
      //批量删除 批量审核 批量打印
      batchStatus: true,
      //供应方式
      optionsSupplyType: [],
      // 单据总条数
      total: 0,
      //业务状态
      optionsworkStatus: [],
      //单据状态
      optionsinvoiceStatus: [],
      //用料方式
      optionsInvInType: [],
      //供应方式
      optionsSupplyType: [],
      // 单据最大高度
      maxHeight: null,
      //单据数据
      tableData: [],
      // 已选单据编码
      codeArr: [],
      //详情抽屉
      drawerTitle: "",
      drawer: false,
      isDrawer: null,
      direction: "rtl",
      drawerData: null,
      drawerTableData: [],
      drawerCustomer: {
        omOrderSalveList: [],
      },
      materialStatus: false,
      drawerMaterial: {}, //物料信息
      drawerTableLoading: true,
      drawerTableKey: "",
      drawerTableMaxHeight: null,
      optionsDensityCode: [],
      // 明细遮罩层
      detailLoading: true,
      //单据参数信息
      parametersSetting: {
        decimalQuantity: "2", //数量小数位数
        decimalPrice: "2",
      },
      //明细查询参数
      queryDetail: {
        pageNum: 1,
        pageSize: 100,
        mpCode: "", //订单号
        ppNumber: "", //销售单号
        invName: "",
        invCode: "", //物料编码
        startDate: "",
        endDate: "",
        workType: this.$route.query.workType,
      },

      // 小数位数
      decimal: 2,
      // 明细总条数
      detailTotal: 0,
      //明细表格key
      tableKey2: "",
      // 明细最大高度
      detailMaxHeight: null,
      //物料大类数据
      sortData: [],
      //物料大类下标
      sortIndex: null,
      //明细数据
      detailTableData: [],
    };
  },

  created() {
    this.getDictionaryType().then(() => {
      this.getDetailList();
    });
  },

  activated() {
    const refresh = this.$store.getters["planStatus/getMbomRefresh"];
    if (refresh == true && this.detailStatus == true) {
      this.$store.dispatch("planStatus/setMbomRefresh", false);
      this.getDetailList();
    } else if (refresh == true && this.detailStatus == false) {
      this.$store.dispatch("planStatus/setMbomRefresh", false);
      this.getBillList();
    }
  },

  methods: {
    // 明细按钮
    detailView() {
      this.detailStatus = true;
      this.handleCheckleDetail();
    },

    // 获取单据
    getBillList() {
      this.loading = true;
      listBill(this.queryParams).then((res) => {
        if (res.code == 200) {
          if (res.rows.length > 0) {
            let list = JSON.parse(JSON.stringify(res.rows));
            let last = this.inMaterTime(list[0].invoiceDate),
              tag = 0;
            list.forEach((item, i) => {
              item.invoiceDate = this.inMaterTime(item.invoiceDate);
              if (list[i].invoiceDate !== last) {
                if (tag == 1) {
                  tag = 0;
                } else if (tag == 0) {
                  tag = 1;
                }
              }
              list[i].tag = tag;
              last = list[i].invoiceDate;
            });
            this.tableData = list;
            console.log(this.tableData);
          } else {
            this.tableData = [];
          }
          this.total = res.total;
          this.tableKey = Math.random();
          this.maxHeight = `${document.documentElement.clientHeight}` - 270;
          this.loading = false;
        }
      });
    },

    // 获取业务状态
    getWorkStatus() {
      dictMatching("sys_work_status")
        .then((res) => {
          if (res.code == 200) {
            this.optionsworkStatus = res.data;
          }
        })
        .catch((err) => {
          this.msgError("获取单据状态失败");
        });
    },

    // 获取单据状态
    getInvoiceStatus() {
      dictMatching("sys_invoice_status")
        .then((res) => {
          if (res.code == 200) {
            this.optionsinvoiceStatus = res.data;
          }
        })
        .catch((err) => {
          this.msgError("获取单据状态失败");
        });
    },

    //搜索单据
    searchList(type) {
      // 日期转换
      if (
        this.valueDate !== undefined &&
        this.valueDate !== null &&
        this.valueDate.length > 0
      ) {
        if (this.detailStatus == false) {
          this.queryParams.startDate = this.parseTime(this.valueDate[0]);
          this.queryParams.endDate = this.setTime(this.valueDate[1]);
        } else {
          this.queryDetail.startDate = this.parseTime(this.valueDate[0]);
          this.queryDetail.endDate = this.setTime(this.valueDate[1]);
        }
      } else {
        if (this.detailStatus == false) {
          this.queryParams.startDate = "";
          this.queryParams.endDate = "";
        } else {
          this.queryDetail.startDate = "";
          this.queryDetail.endDate = "";
        }
      }
      if (type == "bill") {
        this.queryParams.mpCode = this.searchForm.mpCode;
        this.queryParams.workStatus = this.searchForm.workStatus;
        this.queryParams.invoiceStatus = this.searchForm.invoiceStatus;
        this.getBillList();
      } else if (type == "detail") {
        this.queryDetail.mpCode = this.searchForm.mpCode;
        this.queryDetail.ppNumber = this.searchForm.ppNumber;
        this.queryDetail.workType = this.$route.query.workType;
        this.queryDetail.invName = this.searchForm.invName;
        this.queryDetail.invCode = this.searchForm.invCode;
        this.getDetailList();
      }
    },

    // 查询所有
    handleCheckleAll() {
      this.checkClearAll().then(() => {
        this.getBillList();
      });
    },

    // 新增
    jumpAdd() {
      this.$router.push({
        path: "/mp/plan/mbomadd",
        query: {
          open: "addStatus",
          workType: this.$route.query.workType,
          fmConfig: this.$route.query.fmConfig,
          timeStamp: new Date().getTime(),
        },
      });
    },

    // 查看详情
    jumpDetail(code) {
      this.$router.push({
        path: "/mp/plan/mbomview",
        query: {
          detailCode: code,
          open: "seeStatus",
          workType: this.$route.query.workType,
          fmConfig: this.$route.query.fmConfig,
          timeStamp: new Date().getTime()
        },
      });
    },

    // 编辑
    jumpUpdate(code) {
      this.$router.push({
        path: "/mp/plan/mbomedit",
        query: {
          detailCode: code,
          open: "updateStatus",
          workType: this.$route.query.workType,
          fmConfig: this.$route.query.fmConfig,
          timeStamp: new Date().getTime()
        },
      });
    },

    //批量选择
    handleSelectionChange(row) {
      this.codeArr = [];
      if (row.length > 0) {
        this.batchStatus = false;
        row.forEach((obj) => {
          this.codeArr.push({
            mpCode: obj.mpCode,
          });
        });
      } else {
        this.batchStatus = true;
      }
    },

    // 批量审核
    batchExamine() {
      console.log(this.codeArr);
      this.$confirm("确认审核选中领料单", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return examineBill(this.codeArr);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("审核成功");
            this.getBillList();
          }
        });
    },

    // 批量反审核
    batchDeExamine() {
      this.$confirm("确认撤销审核选中领料单", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return examineDeBill(this.codeArr);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("撤销成功");
            this.getBillList();
          }
        });
    },

    //批量删除
    batchDelete() {
      this.$confirm("确认删除选中领料单", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteBill(this.codeArr);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.getBillList();
          }
        });
    },

    // 删除
    handleDelete(row) {
      let arr = [];
      arr.push({
        mpCode: row.mpCode,
      });
      this.$confirm("确认删除", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteBill(arr);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.getBillList();
          }
        });
    },

    // 单据按钮
    billView() {
      this.detailStatus = false;
      this.handleCheckleAll();
    },

    // 清空单据/明细搜索条件
    checkClearAll() {
      return new Promise((resolve, reject) => {
        this.queryParams = {
          pageNum: 1,
          pageSize: 100,
          mpCode: "", //单据编码
          workStatus: "",
          invoiceStatus: "", //单据状态
          startDate: "",
          endDate: "",
          workType: this.$route.query.workType,
        };
        this.valueDate = [];
        this.sortIndex = null;
        // 搜索表单
        this.searchForm = {
          mpCode: "", //单据编码
          ppNumber: "",
          startDate: "",
          endDate: "",
          invoiceStatus: "",
          invName: "", //物料名称
          invCode: "", //物料编码
          workStatus: "", //业务状态
        };
        this.queryDetail = {
          pageNum: 1,
          pageSize: 100,
          mpCode: "", //单据编码
          ppNumber: "",
          invName: "",
          invCode: "",
          startDate: "",
          endDate: "",
          workType: this.$route.query.workType,
        };
        resolve();
      });
    },

    // 获取明细
    getDetailList() {
      return new Promise((resolve, reject) => {
        this.detailLoading = true;
        listBill(this.queryDetail).then((res) => {
          if (res.code == 200) {
            this.detailLoading = false;
            this.detailTotal = res.total;
            this.tableKey2 = Math.random();
            this.detailMaxHeight = null;
            if (res.rows.length > 0) {
              let list = JSON.parse(JSON.stringify(res.rows));
              let last = list[0].mpOrderCode,
                tag = 0;
              list.forEach((item, i) => {
                if (list[i].mpOrderCode !== last) {
                  if (tag == 1) {
                    tag = 0;
                  } else if (tag == 0) {
                    tag = 1;
                  }
                }
                list[i].tag = tag;
                last = list[i].mpOrderCode;
              });
              this.detailTableData = list;
              this.getDecimal();
            } else {
              this.$refs["tableDetailHeight"].doLayout();
              this.detailTableData = [];
            }

            this.detailMaxHeight =
              `${document.documentElement.clientHeight}` - 270;
          }
        });
      });
    },

    //查询所有明细
    handleCheckleDetail() {
      this.checkClearAll().then(() => {
        this.getDetailList().then(() => {
          this.$refs.tableDetailHeight.clearFilter();
        });
      });
    },

    //导出
    handleExport() {
      const queryParams = this.queryDetail;
      this.$confirm("是否确认导出当前生产领料单?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportDetail(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    //筛选供货方式
    supplyChange(value) {
      this.detailTableData = [];
      this.getDetailList();
      this.$refs["tableDetailHeight"].doLayout();
    },

    /* 变色 */
    tableRowClassName({ row, rowIndex }) {
      if (row.tag == 1) {
        return "warning-row";
      }
    },

    //格式化数量单价金额小数位数
    getDecimal() {
      if (this.detailTableData.length > 0) {
        this.detailTableData.forEach((item) => {
          if (item.price !== null && item.price !== undefined) {
            item.price = parseFloat(item.price).toFixed(2);
          }
          if (item.quantity !== null && item.quantity !== undefined) {
            item.quantity = parseFloat(item.quantity).toFixed(2);
          }
          if (item.invQuantity !== null && item.invQuantity !== undefined) {
            item.invQuantity = parseFloat(item.invQuantity).toFixed(2);
          }
          if (item.wi_quantity !== null && item.wi_quantity !== undefined) {
            item.wi_quantity = parseFloat(item.wi_quantity).toFixed(2);
          }
          if (item.wiQuantity !== null && item.wiQuantity !== undefined) {
            item.wiQuantity = parseFloat(item.wiQuantity).toFixed(2);
          }
        });
      }
      if (this.drawerTableData.length > 0) {
        this.drawerTableData.forEach((item) => {
          if (item.quantity !== null && item.quantity !== undefined) {
            item.quantity = parseFloat(item.quantity).toFixed(
              this.parametersSetting.decimalQuantity
            );
          }
          if (item.wi_quantity !== null && item.wi_quantity !== undefined) {
            item.wi_quantity = parseFloat(item.wi_quantity).toFixed(2);
          }
        });
      }
    },

    //获取单据参数
    getParameters() {
      return new Promise((resolve, reject) => {
        billParameters({
          formPath: this.$route.query.fmConfig,
        }).then((res) => {
          if (res.code == 200) {
            if (this.parametersSetting.decimalQuantity !== "null") {
              this.parametersSetting.decimalQuantity =
                res.data["precision.quantity"];
            }
            if (this.parametersSetting.decimalPrice !== "null") {
              this.parametersSetting.decimalPrice = res.data["precision.price"];
            }
            resolve();
          }
        });
      });
    },

    //获取密度单位
    getDensityCode() {
      return new Promise((resolve) => {
        dictMatching("inv_density_type").then((res) => {
          if (res.code == 200) {
            this.optionsDensityCode = res.data;
            resolve();
          }
        });
      });
    },

    //字典数据
    getDictionaryType() {
      return new Promise((resolve) => {
        const _self = this;
        //并行请求
        axios
          .all([
            //归集方式
            dictMatching("inv_supply_type"),
          ])
          .then(
            axios.spread(function (resSupplyType) {
              if (resSupplyType.code == 200) {
                //归集方式
                _self.optionsSupplyType = resSupplyType.data;
                resolve();
              } else {
                _self.msgError("获取信息失败");
              }
            })
          );
      });
    },
    //获取
    getInvInType() {
      return new Promise((resolve) => {
        dictMatching("inv_in_type").then((res) => {
          if (res.code == 200) {
            this.optionsInvInType = res.data;
            resolve();
          }
        });
      });
    },

    //关联详情
    handleDawer(row) {
      if (row.ppNumber !== "" && row.ppNumber !== null) {
        this.materialStatus = true;
      } else {
        this.materialStatus = false;
      }
      if (this.drawer == false || this.isDrawer !== row) {
        this.isDrawer = row;
        this.drawer = true;
      } else if (this.drawer == true && this.isDrawer == row) {
        this.drawer = false;
        return false;
      }
      const self = this;
      this.drawerTitle = row.mpCode + " " + "-" + " " + row.invName;
      this.drawerData = row;
      this.drawerTableLoading = true;

      //并行请求
      axios
        .all([
          //查询销售订单号
          listCode({
            ppNumber: row.ppNumber,
          }),
          //查询关联
          listLink({
            uniqueId: row.uniqueId,
          }),
        ])
        .then(
          axios.spread(function (resCode, resLink) {
            if (resCode.code == 200 && resLink.code == 200) {
              if (resCode.data !== undefined) {
                self.drawerCustomer = resCode.data;
                if (resCode.data.omOrderSalveList.length > 0) {
                  resCode.data.omOrderSalveList.forEach((item) => {
                    self.optionsDensityCode.forEach((obj) => {
                      if (item.densityCode == obj.dictValue) {
                        item.densityCode = obj.dictLabel;
                      }
                    });
                  });

                  self.drawerMaterial = resCode.data.omOrderSalveList[0];
                }
              } else {
                self.drawerCustomer = {
                  omOrderSalveList: [],
                };
                self.drawerMaterial = {};
              }
              self.drawerTableData = resLink.rows;
              self.getDecimal();
              if (self.materialStatus == true) {
                self.drawerTableMaxHeight =
                  `${document.documentElement.clientHeight}` - 340;
              } else {
                self.drawerTableMaxHeight =
                  `${document.documentElement.clientHeight}` - 175;
              }
              self.drawerTableLoading = false;
            } else {
              self.msgError("查询关联物料信息失败");
            }
          })
        );
    },

    //上一条下一条
    btnForward(data, type) {
      let num = this.drawerCustomer.omOrderSalveList.indexOf(data);
      if (type == "next") {
        let addNum = num + 1;
        if (addNum < this.drawerCustomer.omOrderSalveList.length) {
          this.drawerMaterial = this.drawerCustomer.omOrderSalveList[addNum];
        } else {
          this.msgError("当前是最后一条");
        }
      } else {
        let reduceNum = num - 1;
        if (reduceNum >= 0) {
          this.drawerMaterial = this.drawerCustomer.omOrderSalveList[reduceNum];
        } else {
          this.msgError("当前是第一条");
        }
      }
    },

    //关闭抽屉
    handleClose() {
      this.drawer = false;
    },

    //关联跳转
    handleViewBill(row) {
      if (row.invoice == "mp_invoice_type" && row.invoice_id == "0") {
        this.$router.push({
          path: "/mp/plan/orderview",
          query: {
            detailCode: row.code,
            open: "seeStatus",
            workType: row.type_id,
            fmConfig: row.form_config,
          },
        });
      } else if (row.invoice == "prs_invoice_type" && row.invoice_id == "1") {
        this.$router.push({
          path: "/prs/production/productview",
          query: {
            detailCode: row.code,
            open: "seeStatus",
            workType: row.type_id,
            fmConfig: row.form_config,
            timeStamp: new Date().getTime()
          },
        });
      }
    },

    inMaterTime(date) {
      let time = new Date(date);
      return (
        time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate()
      );
    },

    //时间+23时59分59秒
    setTime(date) {
      date.setHours(date.getHours() + 23);
      date.setMinutes(date.getMinutes() + 59);
      date.setSeconds(date.getSeconds() + 59);
      let time = new Date(date);
      return (
        time.getFullYear() +
        "-" +
        (time.getMonth() + 1) +
        "-" +
        time.getDate() +
        " " +
        time.getHours() +
        ":" +
        time.getMinutes() +
        ":" +
        time.getSeconds()
      );
    },
  },

  filters: {
    //时间格式化
    inMaterTime(date) {
      let time = new Date(date);
      return (
        time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate()
      );
    },
    filterDeliver(status) {
      switch (status) {
        case "0":
          return "预计";
          break;
        case "1":
          return "确认";
          break;

        default:
          return "";
      }
    },
    getInvoice(status) {
      switch (status) {
        case "0":
          return "开立";
          break;
        case "1":
          return "审核";
          break;
        case "2":
          return "退回";
          break;
        default:
          return "";
      }
    },
  },
};
</script>
<style lang="scss">
.layout-box {
  .el-link.is-underline:hover:after {
    border: none;
  }
  .supply-box {
    position: absolute;
    right: -10px;
    .el-radio {
      margin-right: 15px;
    }
  }
  .piece-box {
    .el-input__inner {
      padding-right: 0;
      padding-left: 0;
    }
    .el-input.is-disabled .el-input__inner {
      background: none;
      border: none;
      color: #606266;
      height: auto;
      line-height: inherit;
      text-align: center;
    }
    i {
      display: none;
    }
  }
  .plan-status {
    display: flex;
    justify-content: space-around;
  }

  .el-switch.is-disabled .el-switch__core,
  .el-switch.is-disabled .el-switch__label {
    cursor: Default;
  }
  .el-range-editor--medium.el-input__inner {
    height: 32px;
    width: 100%;
  }
  .el-table .warning-row {
    background-color: #f5f7fa;
  }
  .sort-active {
    background: #1890ff !important;
    border-color: #1890ff !important;
    color: #ffffff !important;
  }

  .order-tab {
    .el-tabs__header {
      margin-bottom: 10px;
    }

    .el-textarea__inner {
      min-height: 115px;
      height: 115px;
      padding: 10px;
    }

    .is-disabled .el-textarea__inner {
      background: #fff;
      color: #333;
    }
  }
  .con-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .material-sort {
    span {
      font-size: 14px;
      padding: 0px 15px;
      background: #f4f4f5;
      color: #999;
      display: inline-block;
      border-radius: 3px;
      margin-left: 5px;
      margin-right: 5px;
      cursor: pointer;
      line-height: 26px;
      border: 1px solid #e9e9eb;
    }
  }

  .ware-sel {
    width: 150px;

    .el-input__inner {
      height: 28px;
      line-height: 28px;
    }

    .el-input--medium .el-input__icon {
      line-height: 28px;
    }
  }

  .el-input--medium .el-input__icon {
    line-height: 34px;
  }

  .el-table__header-wrapper th,
  .el-table .el-table__fixed-header-wrapper th {
    height: 35px;
  }

  .has-gutter {
    .el-checkbox__inner {
      margin-right: 4px;
    }
  }

  .el-table tbody tr:hover > td {
    background: none !important;
  }

  .search-box {
    display: flex;
    margin-bottom: 20px;

    .search-input {
      display: flex;
      margin-right: 15px;

      .input-data {
        min-width: 200px !important;
        width: 200px;
      }

      .picker-data {
        min-width: 120px !important;
        width: 120px;
      }
      .el-range-editor--medium .el-range__icon,
      .el-range-editor--medium .el-range__close-icon,
      .el-range-editor--medium .el-range-separator {
        line-height: 24px;
      }
      .el-input {
        margin-right: 15px;
      }
    }
  }

  .el-table th {
    height: 35px;
  }

  .el-table--medium th,
  .el-table--medium td {
    padding: 4px 0;
    padding-bottom: 3px;
  }

  .el-link--inner {
    margin-left: 3px;
    margin-right: 3px;
    font-size: 12px;
  }
  .el-drawer__wrapper {
    width: 958px;
    left: inherit;
  }
  .po-drawer-detail {
    .el-drawer.rtl {
      height: calc(100vh - 85px);
      top: auto;
    }

    .el-drawer__header {
      span {
        color: #333;
        font-size: 16px;
      }

      // text-align: center;
      margin-bottom: 12px;
    }

    .drawer-detail-table {
      padding: 0 15px;
    }

    .drawer-list-box {
      padding: 0 15px 0 0px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;

      .drawer-content {
        p {
          margin: 5px 0px 0px 0;
          label {
            font-size: 14px;
            color: #999;
            width: 70px;
            display: inline-block;
            font-weight: normal;
          }

          .la-width {
            width: 43px !important;
          }

          span {
            font-size: 14px;
            flex: 1;
          }
        }
        .drawer-box {
          .awer-l {
            float: left;
            width: 45%;
          }
          .content-t {
            display: flex;
          }
          .awer-r {
            float: left;
            width: 54%;
            margin-left: 1%;
            .con-price {
              p {
                display: flex;
                align-items: center;
                margin-right: 20px;
              }
            }

            .con-height {
              p {
                display: flex;
                height: 36px;
                span {
                  // height: 40px;
                  text-overflow: -o-ellipsis-lastline;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  line-clamp: 2;
                  -webkit-box-orient: vertical;
                }
              }
            }
          }
        }
      }

      .drawer-number {
        flex: 0 1 20% !important;

        tr td:nth-of-type(1) {
          width: 50% !important;
        }
      }

      .drawer-table {
        flex: 1;
        margin-left: 15px;
        position: relative;
        .drawer-next {
          position: absolute;
          right: 0;
          font-size: 14px;
          top: 12px;
          z-index: 8;
        }
      }

      .inv-table {
        flex: 0 1 58%;
      }

      h2 {
        font-size: 14px;
        margin-top: 10px;
        margin-bottom: 5px;
        margin-left: 10px;
      }

      .box-bottom {
        margin-bottom: 15px;
      }

      p {
        margin: 8px 0;
        font-size: 15px;
      }

      .table-border {
        background-color: #f7f7f8;
        border-radius: 5px;
        padding: 8px 0;
        min-height: 130px;
      }

      table {
        width: 100%;

        td {
          text-align: left;
          padding: 2px 10px;
          font-size: 14px;
          // width: 50%;
        }

        tr td:nth-of-type(1) {
          color: #999;
        }
      }

      .table-left {
        tr td:nth-of-type(1) {
          width: 28%;
        }
      }

      .table-right {
        tr td:nth-of-type(1) {
          width: 20%;
        }
      }
    }
  }
}

.tip-box1 {
  text-align: center;
  width: 100%;

  span {
    color: #515a6e;
    font-size: 14px;
  }
}
.v-modal {
  display: none;
}

:focus {
  outline: 0;
}
</style>
